<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="nav">
      <a href="#page1">page1</a>
      <a href="#page2">page2</a>
      <a href="#page3">page3</a>
    </div>
    <div id="container"></div>
    <script>
      class HashRouter {
        constructor() {
          this.routers = {};
          console.log('2222')
          window.addEventListener('hashchange', this.load.bind(this), false);
        }
        // 用于注册不同的视图
        register(hash, cb) {
          this.routers[hash] = cb;
        }

        // 用于注册首页
        registerIndex(cb) {
          this.routers['index'] = cb;
        }

        // 用于处理视图未找到的情况
        registerNotFound(cb) {
          this.routers['404'] = cb;
        }

        // 用于处理异常情况
        registerError(cb) {
          this.routers['error'] = cb;
        }

        // 用于调用不同视图的回调函数
        load() {
          let hash = window.location.hash.slice(1),
            handler;
          console.log(hash, this.routers.hasOwnProperty(hash));
          // 没有hash 默认首页
          if (!hash) {
            handler = this.routers.index;
          } else if (!this.routers.hasOwnProperty(hash)) {
            // 未找到对应的hash值
            handler = this.routers['404'];
          } else {
            handler = this.routers[hash];
          }
          console.log(handler);
          // 执行注册的回调函数
          try {
            handler();
          } catch (err) {
            console.log(err);
            this.routers['error'].call(this);
          }
        }
      }

      let router = new HashRouter();
      let container = document.querySelector('#container');
      console.log(router);
      // 注册首页回调函数
      router.registerIndex(() => {
        container.innerHtml = '我是首页';
      });
      router.registerNotFound(() => {
        container.innerHtml = '404';
      });
      router.registerError(() => {
        container.innerHtml = 'error';
      });

      router.register('page1', () => (container.innerHTML = '我是page1'));
      router.register('page2', () => (container.innerHTML = '我是page2'));
      router.register('page3', () => (container.innerHTML = '我是page3'));

      // 加载视图
      router.load();
    </script>
  </body>
</html>
